<template>
  <!-- 查询表单 -->
  <el-form
    ref="formSearchRef"
    label-width="100px"
    :inline="true"
    :model="formSearch"
    class="data-grid-search-form"
  >
    <el-row>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item label="商品编号">
          <el-input v-model="formSearch.goodsId" placeholder="">
            <!-- 输入框如果要和下拉对齐宽度，需要增加图标 -->
            <template #suffix>
              <el-icon> </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item label="商品种类">
          <el-select v-model="formSearch.goodsClass" placeholder="商品种类">
            <el-option label="Zone one" value="shanghai"></el-option>
            <el-option label="Zone two" value="beijing"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item label="商品名称">
          <el-input v-model="formSearch.goodsName"
            ><template #suffix>
              <el-icon class="el-input__icon">
                <edit />
              </el-icon> </template
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item label="上架时间">
          <el-input
            v-model="formSearch.goodsPubDate"
            placeholder="Pick a date"
            :suffix-icon="Calendar"
          />
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item label="商品地址">
          <el-select v-model="formSearch.goodsAddress">
            <el-option label="Zone one" value="shanghai"></el-option>
            <el-option label="Zone two" value="beijing"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item label="商品售价">
          <el-input v-model="formSearch.goodsSale" placeholder="Approved by"
            ><template #suffix> <el-icon> </el-icon> </template
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item style="float: right">
          <el-button type="primary" @click="handleSearch">查 询</el-button>
          <el-button @click="handleSearch">重 置</el-button>
          &nbsp; &nbsp;
          <el-link
            type="primary"
            :underline="false"
            @click="searchInputExpland = !searchInputExpland"
          >
            <template v-if="searchInputExpland">
              收起 &nbsp; <el-icon><arrow-up /></el-icon>
            </template>
            <template v-if="!searchInputExpland">
              展开 &nbsp; <el-icon><arrow-down /></el-icon>
            </template>
          </el-link>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <data-grid
    ref="dataGridRef"
    id="dataGridDemo"
    title="data grid 列表"
    show-header="false"
    defaultSort="descending"
    defaultSortBy="lockerDoorId"
    :request="handleLoadGrid"
    :rowSelectCurrentChange="handleRowSelectCurrentChange"
    @onRowSelectCurrentChange="handleRowSelectCurrentChange"
    :rowSelectionChange="handleRowSelectionChange"
    @onRowSelectionChange="handleRowSelectionChange"
    :columns="state.columns"
    :buttons="state.buttons"
  >
    <!-- 自定义模板，会替换控件中的 buttonSlot id：button 仅在当前作用域有效 -->
    <template #button-primary="button">
      <el-button size="mini" type="primary" :icon="Plus" @click="handleAdd"
        >新增</el-button
      >
      <el-button size="mini" :icon="Edit" @click="handleEdit">编辑</el-button>
      <el-button size="mini" :icon="Delete" @click="handleDelete"
        >删除</el-button
      >
    </template>
    <template #button-other="button">
      <el-button size="mini" :icon="Download"> 导出</el-button>
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 info 仅在当前作用域有效 -->
    <template #info="slotProps">
      {{ slotProps.item.title }}&nbsp;
      <el-popover
        placement="top"
        :width="200"
        trigger="click"
        content="编号说明xxx \r\n <br> 可以看到 element 提供的弹出框没有提供换行的功能"
      >
        <template #reference>
          <el-icon style="vertical-align: sub; cursor: pointer"
            ><Warning
          /></el-icon>
        </template>
      </el-popover>
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 goodsName 仅在当前作用域有效 -->
    <template #goodsName="slotProps">
      <el-link type="primary" @click="handleView(slotProps.row)">{{
        slotProps.row.goodsName
      }}</el-link>
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 image 仅在当前作用域有效 -->
    <template #image="slotProps">
      <el-image
        style="width: 100px; height: 30px"
        :src="slotProps.row.goodsImg"
        fit="cover"
      ></el-image>
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 operate 仅在当前作用域有效 -->
    <template #operate="slotProps">
      <el-link type="primary">编辑</el-link> &nbsp;
      <el-link
        type="primary"
        :title="slotProps.item.title"
        @click="handleDelete(slotProps.row.goodsId)"
        >删除
      </el-link>
    </template>
  </data-grid>

  <edit-form ref="editFormRef" @on-submit="onEditSubmit"></edit-form>
  <view-form
    ref="viewFormRef"
    @on-close="onViewClose"
    title="查看商品信息"
  ></view-form>
</template>
<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs } from "vue";
import DataGrid from "@/components/DataGrid.vue";
import EditForm from "./edit.vue";
import ViewForm from "./view.vue";
import { get, post } from "../../../utils/request";
import {
  Download,
  Edit,
  Plus,
  Warning,
  ArrowDown,
  ArrowUp,
  Calendar,
  Delete,
} from "@element-plus/icons-vue";
import { h } from "vue";
import { ElMessageBox, Action, ElNotification } from "element-plus";
import utils from "../../../utils/utils";
import apiDemo from "../api";
// 变量必须和属性 ref 的值相同
const formSearchRef = ref();
const dataGridRef = ref();
const editFormRef = ref();
const viewFormRef = ref();
// 展开收缩
const searchInputExpland = ref(false);

const state = reactive({
  // 表格列配置，大部分属性跟el-table-column配置一样
  columns: [
    {
      field: "goodsId",
      type: "selection",
      align: "center",
      // 冻结列
      fixed: true,
      width: 55,
    },
    {
      title: "序号",
      field: "goodsId",
      type: "index",
      align: "center",
      fixed: true,
      width: 55,
    },
    { title: "商品编号", field: "goodsId", titleSlot: "info", fixed: true },
    {
      title: "商品种类",
      field: "goodsClass",
      sortable: true,
      resizable: true,
      width: 180,
    },
    {
      title: "商品名称",
      field: "goodsName",
      tdSlot: "goodsName",
      sortable: true,
    },
    { title: "商品地址", field: "goodsAddress" },
    { title: "商品等级评价", field: "goodsStar" },
    { title: "商品图片", field: "goodsImg", tdSlot: "image", hidden: true },
    {
      title: "商品售价",
      field: "goodsSale",
      formatter: function (
        row: any,
        column: any,
        cellValue: string,
        index: number
      ) {
        return "￥" + cellValue;
      },
    },
    { title: "上架时间", field: "goodsPubDate" },
    { title: "商品状态", field: "goodsState" },
    { title: "操作", field: "goodsId", tdSlot: "operate", fixed: "right" },
  ],
  buttons: [
    {
      type: "primary",
      buttonSlot: "button-primary",
    },
    {
      type: "primary",
      buttonSlot: "button-other",
    },
  ],
  row: null,
});

// 加载数据
const handleLoadGrid = async (params: any) => {
  // console.log("handleLoadGrid params:", params);
  // params 是从表格组件接收的，包含分页和搜索字段，需要补充 query 查询条件信息
  let query = utils.serializeArray(formSearch);
  // console.log("handleLoadGrid query:", query);
  params.query = JSON.stringify(query);
  let data = { rows: [], total: 0 };
  await apiDemo
    .queryProductListing(params)
    .then((respons: any) => {
      // console.log("handleLoadGrid then respons:", respons);
      if (respons != undefined) {
        data = respons.data;
      }
    })
    .catch((err: any) => {
      console.log("数据处理错误", err);
      utils.errorNotification("数据处理错误" + err);
    });

  // 返回数据给表格组件
  return data;
};

// 表格事件，非必须
const handleRowSelectCurrentChange = (
  currentRow: any | undefined,
  oldCurrentRow: any | undefined
) => {
  // console.log("handleRowSelectCurrentChange", currentRow, oldCurrentRow);
};
// 表格事件，非必须
const handleRowSelectionChange = (rows: any | undefined) => {
  // console.log("handleRowSelectionChange", rows);
};

// 删除操作事件
const handleDelete = (id: any) => {
  // console.log(id, typeof id); 正式开发为 string if (typeof id != "number") {
  // 表格按钮触发的情况，默认参数为按钮对象 target
  if (typeof id != "number") {
    // 根据表格使用单行选中还是多行选中，使用不同的方法获取当前选中的表格
    let rows = dataGridRef.value.getCheckRows();
    let row = dataGridRef.value.getCurrentRow();
    if (rows == null || rows.length != 1) {
      ElMessageBox.alert("请选择一条记录", "提示", {
        confirmButtonText: "OK",
        closeOnClickModal: true,
      }).catch(() => {});
      return;
    }

    ElMessageBox.confirm(`确认删除吗? id ${rows[0].goodsId}` + rows[0].goodsId)
      .then(() => {
        handleSearch();
        ElNotification({
          message: h("i", "xx 已删除"),
        });
      })
      .catch(() => {
        // catch error
      });
  } else {
    // 从表格每行右侧链接点击触发的情况
    ElMessageBox.confirm(`确认删除吗? id ${id}` + id)
      .then(() => {
        handleSearch();
        ElNotification({
          message: h("i", "xx 已删除"),
        });
      })
      .catch(() => {
        // catch error
      });
  }
};

// 打开新增页
const handleAdd = () => {
  editFormRef.value.show();
};
// 打开编辑页
const handleEdit = () => {
  //根据表格使用单行选中还是多行选中，使用不同的方法获取当前选中的表格
  let rows = dataGridRef.value.getCheckRows();
  let row = dataGridRef.value.getCurrentRow();
  if (rows == null || rows.length != 1) {
    ElMessageBox.alert("请选择一条记录", "提示", {
      confirmButtonText: "OK",
      closeOnClickModal: true,
    }).catch(() => {});
    return;
  }
  // form.value = rows[0];
  // console.log(rows[0]);
  editFormRef.value.show(rows[0]);
  // editFormRef.value.show(Object.assign({}, rows[0]));
};
// 新增、编辑页确定按钮回调事件
const onEditSubmit = (result: boolean) => {
  // 刷新表格数据
  handleSearch();
  ElNotification({
    message: h("i", "新增、修改 xx 成功"),
  });
};
// 打开详情页
const handleView = (row: any) => {
  viewFormRef.value.show(row);
};
// 详情页关闭事件
const onViewClose = (result: boolean) => {
  // 刷新表格数据
  handleSearch();
  ElNotification({
    message: h("i", "详情页已关闭，根据业务情况进行后续处理"),
  });
};

// 查询区域表单数据
const formSearch = reactive({
  goodsId: "",
  goodsName: "",
  goodsClass: "",
  goodsAddress: "",
  goodsSale: "",
  goodsPubDate: "",
});

// 表单数据
const formInline = reactive({
  user: "",
  region: "",
  goodsPubDate: "",
});

// 刷新表格
const handleSearch = () => {
  dataGridRef.value.loadGridData();
};
</script>
<style></style>
